<!-- 仓库 - 工程数据 - 发货计划 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain @click="handleDelete" v-if="permission.pallet_delete">删 除 </el-button>
        <!-- <el-button type="primary" size="small" icon="el-icon-print" v-if="permission.pallet_print">打印 </el-button> -->
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button icon="el-icon-printer" size="small" type="text" v-if="permission.pallet_print" @click="rowPrint(row)">打印</el-button>
      </template>
      <template slot="infoForm">
        <avue-crud ref="infoCrud" :option="infoOption" :data="infoData" v-model="infoForm" @selection-change="infoSelectionChange"> </avue-crud>
      </template>
      <template slot="info2Form">
        <avue-crud ref="info2Crud" :option="info2Option" :data="info2Data" v-model="info2Form" @selection-change="infoSelectionChange"> </avue-crud>
      </template>
    </avue-crud>
    <el-dialog append-to-body @close="dialogClose()" title="打印" v-if="printInfoModel" :visible.sync="printInfoModel" width="35%">
      <avue-form ref="printForm" v-model="printInfo" :option="printInfoOption"> </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="printSubmit"><i class="el-icon-printer"></i><span>打 印</span></el-button>
        <el-button size="small" @click="dialogClose()"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getList, getDetail, add, update, remove, print } from '@/api/warehouse/pallet-manage';
import { mapGetters } from 'vuex';
export default {
  components: {
    CommonModalTemplate
  },
  mixins: [],
  data() {
    const self = this;
    return {
      pageCode: 'PALLET_MANAGE',
      lookStatus: true, // 查看状态
      disabledEdit: false, // 编辑禁选逻辑
      visibile: false,
      printInfoModel: false,
      printInfo: {},
      tableOption: {},
      timer: new Date().getTime(),
      modalName: '',
      form: {},
      data: [],
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 440px)',
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        labelWidth: 110,
        dialogCustomClass: 'custom-class',
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: true,
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        editBtn: false,
        delBtn: true,
        refreshBtn: true,
        excelBtn: false,
        selection: true,
        dialogDrag: false, // 开启拖拽功能
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '栈板条码',
            prop: 'palletSn',
            search: true,
            maxlength: 30,
            rules: [
              {
                required: true,
                message: '请输入栈板条码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '仓库',
            prop: 'warehouseName'
          },
          {
            label: '储位',
            prop: 'storageName'
          },
          {
            label: '入库时间',
            prop: 'inboundTime'
          },
          {
            label: '出库时间',
            prop: 'outboundTime'
          }
        ]
        // group: [
        //   {
        //     label: '绑定包装信息',
        //     prop: 'sequenceNumberInfo',
        //     arrow: false,
        //     icon: 'el-icon-vertical-bar',
        //     addDisplay: false,
        //     editDisplay: false,
        //     column: [
        //       {
        //         labelWidth: 0,
        //         label: '',
        //         prop: 'info',
        //         span: 24,
        //         hide: true,
        //         formslot: true
        //       }
        //     ]
        //   },
        //   {
        //     label: '发货信息',
        //     prop: 'deliveryInfo',
        //     arrow: false,
        //     icon: 'el-icon-vertical-bar',
        //     addDisplay: false,
        //     editDisplay: false,
        //     column: [
        //       {
        //         labelWidth: 0,
        //         label: '',
        //         prop: 'info2',
        //         span: 24,
        //         hide: true,
        //         formslot: true
        //       }
        //     ]
        //   }
        // ]
      },
      printInfoOption: {
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '打印机',
            prop: 'equipmentName',
            span: 20,
            type: 'search',
            placeholder: '请选择 打印机',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPrintersModal();
            }
          },
          {
            label: '标签模版',
            prop: 'labelTemplateName',
            span: 20,
            type: 'search',
            placeholder: '请选择 标签模板',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateModal();
            }
          }
        ]
      },
      infoForm: {},
      infoSelectionList: [], // 发货产品信息勾选数据
      infoOption: {
        selection: true,
        editBtn: false,
        height: 270,
        border: true,
        menuWidth: 100,
        addBtn: false,
        delBtn: true,
        menu: false,
        tip: false,
        column: [
          {
            label: '包装条码',
            prop: 'sequenceNumber'
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partMasterName'
          },
          {
            label: '包装数量',
            prop: 'quantity'
          },
          {
            label: '操作人',
            prop: 'createUserName'
          },
          {
            label: '绑定时间',
            prop: 'createTime'
          }
        ]
      },
      info2Form: {},
      info2Option: {
        selection: true,
        editBtn: false,
        height: 270,
        border: true,
        menuWidth: 100,
        addBtn: false,
        delBtn: true,
        menu: false,
        tip: false,
        column: [
          {
            label: '发货单',
            prop: 'sheetNo'
          },
          {
            label: '客户名称',
            prop: 'partnerCode'
          },
          {
            label: '操作人',
            prop: 'createUserName'
          },
          {
            label: '发货时间',
            prop: 'createTime'
          }
        ]
      },
      infoData: [],
      info2Data: []
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.pallet_add, false),
        viewBtn: this.vaildData(this.permission.pallet_view, false),
        delBtn: this.vaildData(this.permission.pallet_delete, false),
        editBtn: this.vaildData(this.permission.pallet_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    dialogClose() {
      this.printInfoModel = false;
      this.printInfo = {};
    },
    /**
     * 打印
     */
    async printSubmit() {
      this.$refs.printForm.validate(async (valid, done) => {
        if (valid) {
          print({
            equipmentId: this.printInfo.equipmentId,
            labelTemplateId: this.printInfo.labelTemplateId,
            palletSn: this.printInfo.palletSn
          }).then(() => {
            this.printInfoModel = false;
            this.printInfo = {};
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
          });
          done();
        }
      });
    },
    getSelectedRows(rowData) {
      if (this.modalName === 'printersModal') {
        if (this.printInfoModel) {
          this.$set(this.printInfo, 'equipmentId', rowData.id);
          this.$set(this.printInfo, 'equipmentName', rowData.name);
        }
      } else if (this.modalName === 'labelTemplateModal') {
        if (this.printInfoModel) {
          this.$set(this.printInfo, 'labelTemplateId', rowData.id);
          this.$set(this.printInfo, 'labelTemplateName', rowData.name);
        }
      }
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    rowPrint(row) {
      this.printInfoModel = true;
      this.printInfo.palletSn = row.palletSn;
    },
    rowSave(row, done, loading) {
      add(row)
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '新增栈板成功!'
          });
          done();
        })
        .catch((err) => {
          loading();
        });
    },

    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '编辑成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeClose(done) {
      done();
    },
    beforeOpen(done, type) {
      if (['add'].includes(type)) {
        this.$confirm('确定生成栈板标签?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            return add();
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
          });
        return;
      }
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          let data = res.data.data;
          this.form = data;
          this.infoData = this._map(data.palletPackingList, (item) => {
            return {
              ...this._get(item, 'packing', {}),
              ...item
            };
          });
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    onLoad(page, params = {}) {
      // params.descs = 'create_time';
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 获取打印机
     */
    openPrintersModal() {
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?status=1',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '标签名称',
            prop: 'name',
            search: true
          },
          {
            label: '标签代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'revision'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '打印标签',
            prop: 'fileUrl'
          }
        ]
      };
    }
  }
};
</script>

<style lang="scss">
.custom-class {
  ::v-deep .avue-group__header .avue-group__title {
    font-weight: bold !important;
  }
}
</style>
